package com.groot.common.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.groot.medical.entity.Menu;




@WebFilter(filterName="MenuFilter",urlPatterns="/sys/*")
public class MenuFilter implements Filter {
	
	private static Logger LOGGER = Logger.getLogger(MenuFilter.class);
	

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		//替换uri信息
		//截取路径替换
		System.out.println("_+_+_+:"+request.getRequestURI());
		String requestURI = request.getRequestURI().replace("midecal", "").replaceAll("/+", "/");
		System.out.println("替换之后:"+requestURI);
		//uri非空判断
		if(requestURI == null || requestURI.length()<=0){
			requestURI = "";
		}
		//从session取出该用户权限信息
		List<Menu> menuList = (List<Menu>) request.getSession().getAttribute("menuList");
		System.out.println("大家都来看看:"+menuList);
		//自定义好需要用到的路径
		String contextPath = request.getContextPath();
		String result = contextPath+"/index.do?method=to404";
		//判断用户权限菜单是否为空
		if(menuList == null || (menuList.size()<0)){
			response.sendRedirect(result);
			return;
		}
		//判断请求权限路径是否为空（）
		boolean Flag = false;
		for(Menu menu: menuList){
			//若权限路径为空那么就跳出循环
			if(menu.getMenuUrl()==null || menu.getMenuUrl().isEmpty())
			continue;
			//将session里取出的权限路径逐个与页面传递过来的路径比较
			//满足就放行
			if(menu.getMenuUrl().indexOf(requestURI) !=-1){
				Flag = true;
				chain.doFilter(request, response);
				return;
			}
		}
		if(!Flag){
			response.sendRedirect(result);
			return;
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
